package com.sun.controller.ums;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sun.common.MsResult;
import com.sun.pojo.UmsMenu;
import com.sun.pojo.UmsRole;
import com.sun.service.ums.IUmsRoleService;
import com.sun.vo.PageVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 后台用户角色表 前端控制器
 * </p>
 *
 * @author 妙妙屋
 * @since 2021-12-13
 */
@RestController
@RequestMapping("/role")
public class UmsRoleController {
    @Autowired
    private IUmsRoleService umsRoleService;
    @GetMapping("/list")
    public MsResult list(String keyword,Long pageNum,Long pageSize){
         IPage<UmsRole> page = umsRoleService.selectPage(keyword,pageNum,pageSize);
        //对mybatis-plus返回的结果进行二次封装,封装成页面需要的结果
        PageVo vo = PageVo.pageToVo(page);
        return MsResult.isOkData(vo);
    }

    @PostMapping("/create")
    public MsResult crate(@RequestBody UmsRole umsRole){
        umsRole.setCreateTime(LocalDateTime.now());
        boolean ok = umsRoleService.save(umsRole);
        if(ok){
            return MsResult.isOkMessage("添加角色成功");
        }
        return MsResult.isFail("角色添加失败");
    }
    @ApiOperation(value = "获取角色集合")
    @GetMapping("/listAll")
    public MsResult allRole(String keyword,Long pageNum,Long pageSize){
        List<UmsRole> list = umsRoleService.list();
        return MsResult.isOkData(list);
    }


    @ApiOperation(value = "获取指定角色菜单")
    @GetMapping("/listMenu/{id}")
    public MsResult listMenu(@PathVariable Long id){
        List<UmsMenu> list = umsRoleService.listMenu(id);
        return MsResult.isOkData(list);
    }


    @ApiOperation(value = "给角色分配菜单")
    @PostMapping("/allocMenu")
    public MsResult allocMenu(Long roleId,String menuIds){
        //先要取消该角色的所有菜单
        umsRoleService.deleteAllMenu(roleId);
        //重新给该角色添加菜单
        String[] s = menuIds.split(",");
        // insert into ums_role_menu_relation(role_id,menu_id) values(3,1)
        for (String m : s) {
            Long menuId = Long.parseLong(m);
            umsRoleService.addMenu(roleId,menuId);
        }
        return MsResult.isOkMessage("菜单分配成功");
    }



}

